<template>
  <div class="user-heder">
    <el-button type="primary" @click="handleadd">新增</el-button>
    <el-form :inline="true" :model="formInline">
      <el-form-item label="请输入">
        <el-input placeholder="请输入用户名" v-model="formInline.keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column v-for="item in tableLabel" :key="item.prop" :prop="item.prop" :label="item.label" />
      <el-table-column fixed="right" label="功能" min-width="120">
        <template #="scope">
          <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button link type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination background layout="prev, pager, next" :total="config.total" @current-change='handleCurrent'
      class="fenye" />
  </div>
  <el-dialog v-model="dialogVisible" :title="action == 'add' ? '新增用户' : '编辑用户'" width="35%" :before-close="handleClose">
    <!--需要注意的是设置了:inline="true"，
		会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
		在css进行处理-->
    <el-form :inline="true" :model="formUser" :rules="rules" ref="userForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="select-clearn" label="性别" prop="sex">
            <el-select v-model="formUser.sex" placeholder="请选择" class="xingbie">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker v-model="formUser.birth" type="date" placeholder="请输入" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="formUser.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button type="primary" @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>


<script setup>
// import { tabBarProps } from 'element-plus';
import { ElMessageBox, ElMessage } from 'element-plus';
import { valid } from 'mockjs';
import { ref, getCurrentInstance, onMounted, reactive, shallowReactive, proxyRefs, nextTick } from 'vue'

// 新增用户
const action = ref('add')
// 显示新增列表
const dialogVisible = ref(false)
//获取表单内容
const formUser = reactive({
  // 性别默认为男
  // sex: '1'
})
//表单校验规则
const rules = reactive({
  name: [{ required: true, message: "姓名是必填项", trigger: "blur" }],
  age: [
    { required: true, message: "年龄是必填项", trigger: "blur" },
    { type: "number", message: "年龄必须是数字" },
  ],
  sex: [{ required: true, message: "性别是必选项", trigger: "change", width: '80px' }],
  birth: [{ required: true, message: "出生日期是必选项" }],
  addr: [{ required: true, message: '地址是必填项' }]
})
// handleClose新增按钮点击
const handleClose = () => {
  // 获取表单重置表单内容
  dialogVisible.value = false
  proxy.$refs['userForm'].resetFields()
}

// handleCancel 表单内取消按钮
const handleCancel = () => {
  dialogVisible.value = false
  proxy.$refs['userForm'].resetFields()
}
// 对表单选择日期进行格式化
const timeFormat = (time) => {
  var time = new Date(time)
  var year = time.getFullYear()
  var month = time.getMonth() + 1
  var date = time.getDate()
  function add(m) {
    return m < 10 ? "0" + m : m
  }
  return year + "-" + add(month) + "-" + add(date)
}
// 新增按钮
const handleadd = () => {
  dialogVisible.value = true
  action.value = 'add'
}
// 表单内确定按钮 onSubmit
const onSubmit = () => {
  // 校验表单内内容
  proxy.$refs['userForm'].validate(async (vaild) => {
    if (vaild) {
      let res = null;
      // 格式化时间
      formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(formUser.birth) ? formUser.birth : timeFormat(formUser.birth)
      if (action.value === 'add') {
        res = await proxy.$api.addUser(formUser)
      } else {
        res = await proxy.$api.EditUser(formUser)
      }
      if (res) {
        dialogVisible.value = false
        proxy.$refs['userForm'].resetFields()
        getUserData()
      } else {
        ElMessage({
          showClose: true,
          message: '请正确输入内容',
          type: 'error',
        })
      }
    }
  })
}

// 定义获取数据内容
const { proxy } = getCurrentInstance()
// 编辑按钮 nextTick() 在组件加载完成后执行
const handleEdit = (val) => {
  action.value = 'edit'
  dialogVisible.value = true
  nextTick(() => {
    Object.assign(formUser, { ...val, addr: '' + val.addr })
  })
}
// 获取接口数据
const getUserData = async () => {
  const data = await proxy.$api.getUserData(config)
  // console.log(data)
  tableData.value = data.list.map(item => ({
    ...item,
    sex: item.sex === 1 ? '男' : '女'
  }))
  config.total = data.count
}
// 用户名 搜索
const formInline = reactive({
  keyword: '',
  total: 0,
  page: 1
})
// 获取表单内数据
const tableData = ref([])

// 定义分页函数
const config = reactive({
  name: ''
})
// 分页按钮
const handleCurrent = (page) => {
  config.page = page
  getUserData()
}
// 搜索
const handleSearch = () => {
  config.name = formInline.keyword
  getUserData()

}
// 删除类别中的列
const handleDelete = (val) => {
  ElMessageBox.confirm("你确定要删除吗").then(async () => {
    await proxy.$api.deleteUser({ id: val.id })
    ElMessage({
      showClose: true,
      message: '删除成功',
      type: 'success'
    })
  })
  getUserData()
}
// 获取表单栏的头部
const tableLabel = reactive([
  {
    prop: 'name',
    label: '姓名'
  },
  {
    prop: 'age',
    label: '年龄'
  },
  {
    prop: 'birth',
    label: '出生年月'
  },
  {
    prop: 'sex',
    label: '性别'
  },
  {
    prop: 'addr',
    label: '地址'
  },
])

onMounted(() => {
  getUserData()
})
</script>
<style scoped lang="less">
.user-heder {
  display: flex;
  justify-content: space-between;
}

.table {
  position: relative;
  height: 520px;

  .fenye {
    position: absolute;
    right: 10px;
    bottom: 30px;
  }

  .el-table {
    width: 100%;
    height: 500px;
  }
}

.select-clearn {
  display: flex;

  .xingbie {
    width: 120px;
  }
}
</style>